﻿using Ldt.DataEngine.DataFlowParse.Model;
using Ldt.DataEngine.RuleAssemble;
using LdtDataEngin.ModuleDetail.BaseModule;
using LdtJudge.DataEngine.Common;
using LdtJudge.DataEngine.Common.CommHelp;
using LdtJudge.DataEngine.Common.StringAssemble;
using LdtJudge.DataEngine.Common.XmlUtility;
using LdtJudge.DataEngine.DataBaseStores;
using LdtJudge.DataEngine.Model.DataModel.SysCommon;
using LdtJudge.DataEngine.Model.DataModel.SystemtableModel;
using LdtJudge.DataEngine.Model.ElmentModel;
using LdtJudge.DataEngine.Model.XMLConfigModel.CircumsatanModel;
using LdtJudge.DataEngine.Model.XMLConfigModel.DataStores;
using LdtJudge.DataEngine.Model.XMLConfigModel.SituationPloModel;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Xml;

namespace LdtDataEngin.ModuleDetail.AnalysisModule.SituationPlot
{
    /// <summary>
    /// 情节内容提取
    /// </summary>
    public class ExtPlotData : SituationPlotBaseClass
    {
        /// <summary>
        /// 模块名称
        /// </summary>
        private readonly string _moduleName;


        //[XmlElementAttribute("paragraph", IsNullable = false)]
        public List<ParagraphModel> paragraphModelList = new List<ParagraphModel>();
        /// <summary>
        /// 模块的配置
        /// </summary>
        private CircumsatanModel circumsatanModel = new CircumsatanModel();

        public string casecauseid;

        /// <summary>
        /// 机器学习配置
        /// </summary>
        private SituationPlotMLConfigModel mlConfigModel = null;
        /// <summary>
        /// 匹配整句文本与节点集合
        /// </summary>
        private Dictionary<string, List<CommonPlotorSituation>> dicContent = new Dictionary<string, List<CommonPlotorSituation>>();

        /// <summary>
        /// 匹配拆句文本与节点集合
        /// </summary>
       // private Dictionary<string, List<CommonPlotorSituation>> dicFJContent = new Dictionary<string, List<CommonPlotorSituation>>();

        public ExtPlotData(DataContext dataContext, string moduleName)
        {
            _moduleName = moduleName;
            base.dataContext = dataContext;
            // 根据模块名称获取配置并解析
            var configModel = dataContext.DataLayerSys.GetConfigModel(moduleName);
            if (configModel != null && configModel.ConfigDetail != null && configModel.ConfigDetail.Count > 0)
            {
                string configCode = string.Empty;
                if (moduleName.ToLower().IndexOf("ldtdataengin.moudle.moudlecasecauseelementextract") > -1)
                    configCode = "causeqjextract";
                else if (moduleName.ToLower().IndexOf("ldtdataengin.moudle.moudleplotmatch") > -1)
                    configCode = "qjextract";
                ConfigModel plotConfig = configModel.ConfigDetail.FirstOrDefault(x => x.Code == configCode);
                circumsatanModel = XmlUtility.DeserializeToObject<CircumsatanModel>(plotConfig.ConfigContent);
                ConfigModel mlConfig = configModel.ConfigDetail.FirstOrDefault(x => x.Code.ToLower() == "qxqjmatchlearn");
                if (mlConfig != null)
                {
                    mlConfigModel = XmlUtility.DeserializeToObject<SituationPlotMLConfigModel>(mlConfig?.ConfigContent);
                }
            }

        }
        public ExtPlotData(string ConfigContent) 
        {

            mlConfigModel = XmlUtility.DeserializeToObject<SituationPlotMLConfigModel>(ConfigContent);
        }
        /// <summary>
        /// 根据内容返回匹配后的情节包含公共情节和个罪情节
        /// </summary>
        /// <param name="CauseID">案由ID</param>
        /// <param name="IsDevelopSchedule">匹配状态</param>
        /// <param name="MatchText">内容</param>
        /// <param name="commElement">条件对象</param>
        /// <returns></returns>
        //public void List<CommonPlotorSituation> MatchValueID_f(string CauseID, bool IsDevelopSchedule, string MatchText, CommElementRegexCode commElement)
        //{
        //    List<CommonPlotorSituation> listMPlot = new List<CommonPlotorSituation>();
        //    /////查询公共情节的数据
        //    //string sqlstr = "SELECT * FROM dbo.SYS_CaseCause WHERE  (AllParentId+',' like '%1000,1111111,%' or AllParentId+',' like '%1000,2222222,%') ORDER BY CC_GlobalOrder ";
        //    //List<SYS_CaseCause> CommonTable = dALSYS_CaseCause.GetCaseCauseMatchValueID();
        //    //System.Diagnostics.Stopwatch plotwatch = new System.Diagnostics.Stopwatch();
        //    //plotwatch.Start();


        //    //base.LoopExtractPlotCommon("1000", MatchText, CommonTable, "1000", commElement, ref listMPlot);
        //    //plotwatch.Stop();

        //    ///用来显示个罪情节
        //    int rowindex = listMPlot.Count;
        //    if (!string.IsNullOrWhiteSpace(CauseID))
        //    {
        //        string sqlstrcause = "SELECT * FROM dbo.SYS_CaseCause WHERE  AllParentId LIKE '%," + CauseID + ",%' AND CC_NodeType IN (5,6)";
        //        List<SYS_CaseCause> CommonTableC = dALSYS_CaseCause.GetCaseCauseMatchValueIDByCauseID(CauseID);
        //       // plotwatch.Restart();

        //        if (IsDevelopSchedule)
        //        {
        //            base.LoopExtractPlotCommon(CauseID, MatchText, CommonTableC, CauseID, commElement, ref listMPlot);
        //        }
        //        else
        //        {
        //            base.LoopExtractRuleItem(CauseID, MatchText, CommonTableC, CauseID, commElement, ref listMPlot);
        //        }

        //        ///plotwatch.Stop();

        //    }
        //    return listMPlot;
        //}

        /// <summary>
        /// 根据内容返回匹配后的情节包含公共情节和个罪情节
        /// </summary>
        /// <param name="CauseID">案由ID</param>
        /// <param name="IsDevelopSchedule">匹配状态</param>
        /// <param name="MatchText">内容</param>
        /// <param name="commElement">条件对象</param>
        /// <param name="affirmType">认定意见结果</param>
        /// <param name="district">地域</param>
        /// <returns></returns>
        public override List<CommonPlotorSituation> MatchValueID(string CauseID, bool IsDevelopSchedule, string MatchText, CommElementRegexCode commElement, string affirmType, string district,string isml)
        {
            List<CommonPlotorSituation> listMPlot = new List<CommonPlotorSituation>();
            ///查询公共情节的数据
            string sqlstr = "SELECT * FROM dbo.SYS_CaseCause WHERE  (AllParentId+',' like '%1000,1111111,%' or AllParentId+',' like '%1000,2222222,%') ORDER BY CC_GlobalOrder ";
            List<SYS_CaseCause> CommonTable = dALSYS_CaseCause.GetCaseCauseMatchValueID(isml);
            System.Diagnostics.Stopwatch plotwatch = new System.Diagnostics.Stopwatch();
            plotwatch.Start();


            base.LoopExtractPlotCommon("1000", MatchText, CommonTable, "1000", commElement, affirmType, ref listMPlot);
            plotwatch.Stop();
            RuleParseClass.WriteContentLog("执行查询1000公共情节的数据耗时：" + plotwatch.Elapsed.TotalMilliseconds.ToString("0"));

            ///用来显示个罪情节
            int rowindex = listMPlot.Count;
            if (!string.IsNullOrWhiteSpace(CauseID))
            {
                string sqlstrcause = "SELECT * FROM dbo.SYS_CaseCause WHERE  AllParentId LIKE '%," + CauseID + ",%' AND CC_NodeType IN (5,6)";
                plotwatch.Restart();
                List<SYS_CaseCause> CommonTableC = dALSYS_CaseCause.GetCaseCauseMatchValueIDByCauseID(CauseID);
                plotwatch.Stop();
                RuleParseClass.WriteContentLog("执行查询"+ CauseID + "的数据耗时：" + plotwatch.Elapsed.TotalMilliseconds.ToString("0"));
                // plotwatch.Restart();
                plotwatch.Restart();
                if (IsDevelopSchedule)
                {
                    base.LoopExtractPlotCommon(CauseID, MatchText, CommonTableC, CauseID, commElement, affirmType, ref listMPlot);
                }
                else
                {
                    base.LoopExtractRuleItem(CauseID, MatchText, CommonTableC, CauseID, commElement, affirmType, ref listMPlot);
                }
                plotwatch.Stop();
                RuleParseClass.WriteContentLog("根据内容返回匹配后的情节包含公共情节和个罪情节的数据耗时：" + plotwatch.Elapsed.TotalMilliseconds.ToString("0"));
                if (listMPlot.Count > 0)
                {
                    base.dataContext?.InteractiveShow?.LogShow("      根据原文匹配到的情节如下：");
                    for (int i = 0; i < listMPlot.Count; i++)
                    {
                        var mo = listMPlot[i];
                        base.dataContext?.InteractiveShow?.LogShow(string.Format("      匹配到的 第{0}个 情节为：名称：{1} ,节点ID为：{2}", (i + 1), mo.Common_name, mo.Common_id));
                        //if (!dicFJContent.ContainsKey(mo.Common_originalText.Trim(new char[] { '，', '。' })))
                        //{
                        //    dicFJContent.Add(mo.Common_originalText.Trim(new char[] { '，', '。' }), new List<CommonPlotorSituation> { mo });
                        //}
                        //else if (!dicFJContent[mo.Common_originalText.Trim(new char[] { '，', '。' })].Any(x => x.Common_id == mo.Common_id && x.Common_name == mo.Common_name))
                        //{
                        //    dicFJContent[mo.Common_originalText.Trim(new char[] { '，', '。' })].Add(mo);
                        //}
                    }
                }
            }
            return listMPlot;
        }

        /// <summary>
        /// 公共情节处理
        /// </summary>
        /// <param name="MatchText"></param>
        /// <param name="commElement"></param>
        /// <returns></returns>
        public List<CommonPlotorSituation> CommMatchValueID(string MatchText, CommElementRegexCode commElement, string affirm,string isml)
        {
            List<CommonPlotorSituation> listMPlot = new List<CommonPlotorSituation>();
            ///查询公共情节的数据
            string sqlstr = "SELECT * FROM dbo.SYS_CaseCause WHERE  (AllParentId+',' like '%1000,1111111,%' or AllParentId+',' like '%1000,2222222,%') ORDER BY CC_GlobalOrder ";
            List<SYS_CaseCause> CommonTable = dALSYS_CaseCause.GetCaseCauseMatchValueID(isml);
            System.Diagnostics.Stopwatch plotwatch = new System.Diagnostics.Stopwatch();
            plotwatch.Start();


            base.LoopExtractPlotCommon("1000", MatchText, CommonTable, "1000", commElement, affirm, ref listMPlot);
            plotwatch.Stop();

            return listMPlot;

        }

        #region 情形情节补充

        /// <summary>
        /// 公共能力获取情形情节
        /// </summary>
        /// <param name="paragraphCode">段落编号</param>
        /// <param name="paragraphValue">段落内容</param>
        /// <param name="caseType">案件类型</param>
        /// <param name="docType">文书类型</param>
        /// <param name="caseCauseCode">案由id</param>
        /// <param name="cofige">配置文件</param>
        /// <returns></returns>
        public List<Dictionary<string, string>> MatchSituationSupplementSuperr(string paragraphCode, string paragraphValue, string caseType, string docType, string caseCauseCode, string cofige)
        {
            List<Dictionary<string, string>> rowsdic = new List<Dictionary<string, string>>();
            GetSysCaseCause getSysCaseCause = new GetSysCaseCause();
            List<CaseCauseModel> caseCausesList = new List<CaseCauseModel>();
            if (!string.IsNullOrEmpty(caseCauseCode))
            {
                List<string> causeListvalue = caseCauseCode.Split(',').ToList();
                foreach (string value in causeListvalue)
                {
                    if (!string.IsNullOrWhiteSpace(value))
                    {
                        caseCausesList.Add(getSysCaseCause.GetModel(value));
                    }
                }
            }
            circumsatanModel = XmlUtility.DeserializeToObject<CircumsatanModel>(cofige);
            ParagraphModel paragraphmodel = GetConfigModel(cofige, caseType, docType, paragraphCode);
            if (paragraphmodel != null)
            {
                SituationPlotMLCaseType mlCaseType = null;
                if (mlConfigModel != null)
                {
                    mlCaseType = mlConfigModel.CaseTypes.FirstOrDefault(x => x.Value == caseType);

                }
                foreach (CaseCauseModel causeModel in caseCausesList)
                {
                    string cc_id = causeModel.CC_ID;
                    List<CommonPlotorSituation> models = new List<CommonPlotorSituation>();
                    //执行拆句
                    var sentences = base.SentenceSplitting(paragraphValue, paragraphCode, circumsatanModel, "2", causeModel.CC_ID, false);
                    if (sentences != null && sentences.Any())
                    {
                        List<SentenceModel> regSentences = new List<SentenceModel>();
                        if (paragraphmodel.isml == "1")
                        {
                            Stopwatch swtext1 = new Stopwatch();
                            swtext1.Start();
                            //通过机器学习匹配情节数据
                            List<CommonPlotorSituation> matchLearnModels = base.MatchListByMachLearn(mlCaseType, cc_id, sentences, 2, out regSentences);
                            if (matchLearnModels != null && matchLearnModels.Any())
                                models.AddRange(matchLearnModels);

                            swtext1.Stop();
                        }
                        else
                        {
                            regSentences = sentences;
                        }
                        if (regSentences != null && regSentences.Any())
                        {
                            if (true)
                            {
                                CommElementRegexCode commElement = new CommElementRegexCode();
                                commElement.CaseType = base.dataContext.DataLayerAns.CaseType;
                                commElement.SourceCode = base.dataContext.DataLayerAns.SourceCode;
                                commElement.PargarphCode = paragraphCode.ToLower();
                                commElement.PargarphWhere = "=";
                                commElement.Purpose = ExtractType.plotorsituation;
                                bool isRuleitem = (causeModel.CC_DevelopSchedule == 1 || causeModel.CC_DevelopSchedule == 2) ? true : false;
                                string match = isRuleitem ? "Regex" : "RuleItem";
                                if (regSentences.Any(x => x.SentenceType == "0"))
                                {
                                    string affirmContent = string.Join("", regSentences.Where(x => x.SentenceType == "0").Select(x => x.SentenceContent));
                                    var affirmModels = MatchValueID(cc_id, isRuleitem, affirmContent, commElement, "0", "", paragraphmodel.isml);
                                    if (affirmModels != null && affirmModels.Any())
                                        models.AddRange(affirmModels);
                                }
                                if (regSentences.Any(x => x.SentenceType == "1"))
                                {
                                    string unAffirmContent = string.Join("", regSentences.Where(x => x.SentenceType == "1").Select(x => x.SentenceContent));
                                    var unAffirmModels = MatchValueID(cc_id, isRuleitem, unAffirmContent, commElement, "1", "", paragraphmodel.isml);
                                    if (unAffirmModels != null && unAffirmModels.Any())
                                        models.AddRange(unAffirmModels);
                                }
                            }
                           if (true)
                            {
                                CommElementRegexCode commElement = new CommElementRegexCode();
                                commElement.CaseType = base.dataContext.DataLayerAns.CaseType;
                                commElement.SourceCode = base.dataContext.DataLayerAns.SourceCode;
                                commElement.PargarphCode = paragraphCode.ToLower();
                                commElement.PargarphWhere = "=";
                                commElement.Purpose = ExtractType.plotorsituation;
                                bool isRuleitem = (causeModel.CC_DevelopSchedule == 1 || causeModel.CC_DevelopSchedule == 2) ? true : false;
                                string match = isRuleitem ? "Regex" : "RuleItem";
                                if (regSentences.Any(x => x.SentenceType == "0"))
                                {
                                    string affirmContent = string.Join("", regSentences.Where(x => x.SentenceType == "0").Select(x => x.SentenceContent));
                                    var affirmModels = CommMatchValueID(paragraphValue, commElement, "0", paragraphmodel.isml);
                                    if (affirmModels != null && affirmModels.Any())
                                        models.AddRange(affirmModels);
                                }
                                if (regSentences.Any(x => x.SentenceType == "1"))
                                {
                                    string unAffirmContent = string.Join("", regSentences.Where(x => x.SentenceType == "1").Select(x => x.SentenceContent));
                                    var unAffirmModels = CommMatchValueID(paragraphValue, commElement, "1", paragraphmodel.isml);
                                    if (unAffirmModels != null && unAffirmModels.Any())
                                        models.AddRange(unAffirmModels);
                                }
                            }
                        }
                        if (models != null && models.Any())
                        {
                            //----------------------------------
                            //查询到的对应情节对象列表
                            foreach (var item in models)
                            {///针对相同来源的，相同的情节进行去重处理
                                var rowplottemp = rowsdic.FirstOrDefault(rowplot => LdFormat.GetDicValue(rowplot, "po_plotid") == item.Common_id && LdFormat.GetDicValue(rowplot, "po_plotsource") == paragraphmodel.Type );
                                if (rowplottemp == null)
                                {
                                    Dictionary<string, string> row = new Dictionary<string, string>();
                                    row.Add("plotid", "");
                                    row.Add("po_ismatch", "1");
                                    row.Add("po_singlecrimeid", "");
                                    row.Add("po_matchsource", base.dataContext.DataLayerAns.SourceCode);
                                    row.Add("po_affirmidearesult", item.Common_affirm);
                                    row.Add("po_plotsource", paragraphmodel.Type);
                                    row.Add("po_typeid", item.Common_typeid);
                                    row.Add("po_plotid", item.Common_id);
                                    row.Add("po_plotname", item.Common_name);
                                    row.Add("originaltext", item.Common_originalText);
                                    row.Add("mc_influencetypeid", item.Mc_influencetypeid);
                                    row.Add("CaseCause", causeModel.CC_ID);
                                    List<string> idList = new List<string>();
                                    idList.Add(item.Common_id);
                                    SituationExpressAdd situationExpressAdd = new SituationExpressAdd();
                                    string situationID = situationExpressAdd.GetGroupSituationID(item.Common_id, 1, "1", idList);
                                    string ewid = situationExpressAdd.GetGroupExpressID(situationID, dataContext.DataLayerAns.CaseType);
                                    ///根据组合情节获取表述ID
                                    row.Add("ew_id", ewid);
                                    rowsdic.Add(row);
                                }
                            }
                        }
                    }
                }
                   
            }
            return rowsdic;
        }
        /// <summary>
        /// 情节表数据做补充
        /// </summary>
        public void MatchPlotSupplement(List<DataModel> dataModelAsisModelList, string parid)
        {
            dicContent.Clear();
            //dicFJContent.Clear();
            if (base.dataContext.DataLayerAns.CaseCausesList == null || base.dataContext.DataLayerAns.CaseCausesList.Count() == 0)
            {
                base.dataContext.InteractiveShow.LogShow(" 当前案由未获取到，不进行情节的分析！");
                return;
            }

            base.dataContext.InteractiveShow.LogShow(" *********************@开始情节提取****************************");

            Stopwatch swtext = new Stopwatch();
            swtext.Start();
            //是否机器学习
            bool isMatchLearn = false;
            SituationPlotMLCaseType mlCaseType = null;
            if (mlConfigModel != null)
            {
                mlCaseType = mlConfigModel.CaseTypes.FirstOrDefault(x => x.Value == dataContext.DataLayerAns.CaseType);
                if (mlCaseType != null)
                    isMatchLearn = true;
            }
            RuleParseClass.WriteContentLog("开始情节提取,提取数量为：" + dataContext.DataLayerAns.CaseCausesList.Count);

            foreach (var causeModel in dataContext.DataLayerAns.CaseCausesList)
            {
                List<Dictionary<string, string>> rowsdic = new List<Dictionary<string, string>>();
                Stopwatch s1 = new Stopwatch();
                s1.Start();
                Dictionary<string, List<ForeignKey>> extorgtext = ExtPlotContent(causeModel.CC_ID, "", dataModelAsisModelList, parid);
                base.dataContext.InteractiveShow.LogShow("匹配到的原文为:" + JsonConvert.SerializeObject(extorgtext));
                s1.Stop();
                RuleParseClass.WriteContentLog("情节提取,耗时：" + s1.ElapsedMilliseconds+ "匹配到的原文为:" + JsonConvert.SerializeObject(extorgtext));

                string cc_id = causeModel.CC_ID;
                foreach (var dicorg in extorgtext)
                {
                    foreach (ForeignKey org in dicorg.Value)
                    {
                        List<CommonPlotorSituation> models = new List<CommonPlotorSituation>();
                        //执行拆句
                        s1.Restart();
                        var sentences = base.SentenceSplitting(org.Oringtext, org.paragraphCode, circumsatanModel, "2", causeModel.CC_ID, false);
                        s1.Stop();
                        RuleParseClass.WriteContentLog("拆句,耗时：" + s1.ElapsedMilliseconds + "结果为:" + JsonConvert.SerializeObject(sentences));


                        if (sentences != null && sentences.Any())
                        {
                            List<SentenceModel> regSentences = new List<SentenceModel>();
                            if (isMatchLearn == true && org.isml == "1")
                            {
                                base.dataContext.InteractiveShow.LogShow("使用机器学习开始:" + JsonConvert.SerializeObject(sentences));
                                Stopwatch swtext1 = new Stopwatch();
                                swtext1.Start();
                                //通过机器学习匹配情节数据
                                List<CommonPlotorSituation> matchLearnModels = base.MatchListByMachLearn(mlCaseType, cc_id, sentences, 2, out regSentences);
                                if (matchLearnModels != null && matchLearnModels.Any())
                                    models.AddRange(matchLearnModels);

                                swtext1.Stop();
                                base.dataContext.InteractiveShow.LogShow("使用机器学习调用时长:" + swtext1.Elapsed.TotalMilliseconds.ToString("0"));
                                RuleParseClass.WriteContentLog("使用机器学习调用时长:" + swtext1.Elapsed.TotalMilliseconds.ToString("0"));
                            }
                            else
                            {
                                regSentences = sentences;
                            }
                            if (regSentences != null && regSentences.Any())
                            {
                                if (org.type != "3")
                                {
                                    CommElementRegexCode commElement = new CommElementRegexCode();
                                    commElement.CaseType = base.dataContext.DataLayerAns.CaseType;
                                    commElement.SourceCode = base.dataContext.DataLayerAns.SourceCode;
                                    commElement.PargarphCode = org.paragraphCode.ToLower();
                                    commElement.PargarphWhere = "=";
                                    commElement.Purpose = ExtractType.plotorsituation;
                                    bool isRuleitem = (causeModel.CC_DevelopSchedule == 1 || causeModel.CC_DevelopSchedule == 2) ? true : false;
                                    string match = isRuleitem ? "Regex" : "RuleItem";
                                    base.dataContext.InteractiveShow.LogShow("*进行情节提取：当前案由的匹配规则为：" + match);
                                    if (regSentences.Any(x => x.SentenceType == "0"))
                                    {
                                        s1.Restart();
                                        string affirmContent = string.Join("", regSentences.Where(x => x.SentenceType == "0").Select(x => x.SentenceContent));
                                        //先进行整句的判断，如果整句已经匹配过则不进行重新匹配
                                        if (dicContent.ContainsKey(affirmContent))
                                        {
                                            models.AddRange(dicContent[affirmContent]);
                                        }
                                        else
                                        {
                                            //List<CommonPlotorSituation> regSentencesPp = new List<CommonPlotorSituation>();

                                            ////判断分句里面 是否已经有匹配的，有则去掉已经匹配的
                                            //if (dicFJContent.Count > 0)
                                            //{
                                            //    List<SentenceModel> regSentencesNew = new List<SentenceModel>();
                                            //    regSentences.ForEach(x =>
                                            //    {
                                            //        if (!dicFJContent.ContainsKey(x.SentenceContent.Trim(new char[] { '，', '。' })))
                                            //        {
                                            //            regSentencesNew.Add(x);
                                            //        }
                                            //        else
                                            //        {
                                            //            regSentencesPp.AddRange(dicFJContent[x.SentenceContent.Trim(new char[] { '，', '。' })]);
                                            //        }
                                            //    });
                                            //    affirmContent = string.Join("", regSentencesNew.Where(x => x.SentenceType == "0").Select(x => x.SentenceContent));
                                            //}
                                            var affirmModels = MatchValueID(cc_id, isRuleitem, affirmContent, commElement, "0", "", org.isml);
                                            if (affirmModels != null && affirmModels.Any())
                                                models.AddRange(affirmModels);
                                            //if (regSentencesPp.Any())
                                            //    models.AddRange(regSentencesPp);
                                            if (!dicContent.ContainsKey(affirmContent))
                                            {
                                                dicContent.Add(affirmContent, affirmModels);
                                            }
                                            //sentences.ForEach(x =>
                                            //{
                                            //    if (!dicFJContent.ContainsKey(x.SentenceContent))
                                            //    {
                                            //        dicFJContent.Add(x.SentenceContent, new CommonPlotorSituation());
                                            //    }
                                            //});
                                            s1.Stop();
                                            RuleParseClass.WriteContentLog("进行否定句匹配原文：" + affirmContent + "，耗时：" + s1.Elapsed.TotalMilliseconds.ToString("0") + "结果：" + JsonConvert.SerializeObject(affirmModels));
                                        }
                                    }
                                    if (regSentences.Any(x => x.SentenceType == "1"))
                                    {
                                        s1.Restart();
                                        string unAffirmContent = string.Join("", regSentences.Where(x => x.SentenceType == "1").Select(x => x.SentenceContent));
                                        if (dicContent.ContainsKey(unAffirmContent))
                                        {
                                            models.AddRange(dicContent[unAffirmContent]);
                                        }
                                        else
                                        {
                                            //List<CommonPlotorSituation> regSentencesPp = new List<CommonPlotorSituation>();

                                            //if (dicFJContent.Count > 0)
                                            //{
                                            //    List<SentenceModel> regSentencesNew = new List<SentenceModel>();
                                            //    regSentences.ForEach(x =>
                                            //    {
                                            //        if (!dicFJContent.ContainsKey(x.SentenceContent.Trim(new char[] { '，', '。' })))
                                            //        {
                                            //            regSentencesNew.Add(x);
                                            //        }
                                            //        else
                                            //        {
                                            //            regSentencesPp.AddRange(dicFJContent[x.SentenceContent.Trim(new char[] { '，', '。' })]);
                                            //        }
                                            //    });
                                            //    unAffirmContent = string.Join("", regSentencesNew.Where(x => x.SentenceType == "1").Select(x => x.SentenceContent));
                                            //}
                                            var unAffirmModels = MatchValueID(cc_id, isRuleitem, unAffirmContent, commElement, "1", "", org.isml);
                                            if (unAffirmModels != null && unAffirmModels.Any())
                                                models.AddRange(unAffirmModels);
                                            //if (regSentencesPp.Any())
                                            //    models.AddRange(regSentencesPp);
                                            if (!dicContent.ContainsKey(unAffirmContent))
                                            {
                                                dicContent.Add(unAffirmContent, unAffirmModels);
                                            }
                                            //sentences.ForEach(x =>
                                            //{
                                            //    if (!dicFJContent.ContainsKey(x.SentenceContent))
                                            //    {
                                            //        dicFJContent.Add(x.SentenceContent, new CommonPlotorSituation());
                                            //    }
                                            //});
                                            s1.Stop();
                                            RuleParseClass.WriteContentLog("进行认定句匹配原文：" + unAffirmContent + "，耗时：" + s1.Elapsed.TotalMilliseconds.ToString("0") + "结果：" + JsonConvert.SerializeObject(unAffirmModels));
                                        }
                                    }
                                }
                                else if (org.type == "3")
                                {
                                    CommElementRegexCode commElement = new CommElementRegexCode();
                                    commElement.CaseType = base.dataContext.DataLayerAns.CaseType;
                                    commElement.SourceCode = base.dataContext.DataLayerAns.SourceCode;
                                    commElement.PargarphCode = org.paragraphCode.ToLower();
                                    commElement.PargarphWhere = "=";
                                    commElement.Purpose = ExtractType.plotorsituation;
                                    bool isRuleitem = (causeModel.CC_DevelopSchedule == 1 || causeModel.CC_DevelopSchedule == 2) ? true : false;
                                    string match = isRuleitem ? "Regex" : "RuleItem";
                                    base.dataContext.InteractiveShow.LogShow("*进行情节提取：当前案由的匹配规则为：" + match);
                                    if (regSentences.Any(x => x.SentenceType == "0"))
                                    {
                                        s1.Restart();
                                        string affirmContent = string.Join("", regSentences.Where(x => x.SentenceType == "0").Select(x => x.SentenceContent));
                                        var affirmModels = CommMatchValueID(org.Oringtext, commElement, "0",org.isml);
                                        if (affirmModels != null && affirmModels.Any())
                                            models.AddRange(affirmModels);
                                        s1.Stop();
                                        RuleParseClass.WriteContentLog("进行否定句匹配原文：" + affirmContent + "，耗时：" + s1.Elapsed.TotalMilliseconds.ToString("0") + "结果：" + JsonConvert.SerializeObject(affirmModels));

                                    }
                                    if (regSentences.Any(x => x.SentenceType == "1"))
                                    {
                                        s1.Restart();
                                        string unAffirmContent = string.Join("", regSentences.Where(x => x.SentenceType == "1").Select(x => x.SentenceContent));
                                        var unAffirmModels = CommMatchValueID(org.Oringtext, commElement, "1", org.isml);
                                        if (unAffirmModels != null && unAffirmModels.Any())
                                            models.AddRange(unAffirmModels);
                                        s1.Stop();
                                        RuleParseClass.WriteContentLog("进行认定句匹配原文：" + unAffirmContent + "，耗时：" + s1.Elapsed.TotalMilliseconds.ToString("0") + "结果：" + JsonConvert.SerializeObject(unAffirmModels));

                                    }
                                }
                            }
                            if (models != null && models.Any())
                            {
                                RuleParseClass.WriteContentLog("匹配到的情节数量" + models.Count);
                                s1.Restart();
                                //----------------------------------
                                //查询到的对应情节对象列表
                                foreach (var item in models)
                                {///针对相同来源的，相同的情节进行去重处理
                                    var rowplottemp = rowsdic.FirstOrDefault(rowplot => LdFormat.GetDicValue(rowplot, "po_plotid") == item.Common_id && LdFormat.GetDicValue(rowplot, "po_plotsource") == dicorg.Key && LdFormat.GetDicValue(rowplot, "sp_id") == org.Fk);
                                    if (rowplottemp == null)
                                    {
                                        Dictionary<string, string> row = new Dictionary<string, string>();
                                        row.Add("plotid", "");
                                        row.Add("sp_id", org.Fk);
                                        row.Add("po_ismatch", "1");
                                        row.Add("po_singlecrimeid", "");
                                        row.Add("po_matchsource", base.dataContext.DataLayerAns.SourceCode);
                                        row.Add("po_affirmidearesult", item.Common_affirm);
                                        row.Add("po_plotsource", dicorg.Key);
                                        row.Add("po_typeid", item.Common_typeid);
                                        row.Add("po_plotid", item.Common_id);
                                        row.Add("po_plotname", item.Common_name);
                                        row.Add("originaltext", item.Common_originalText);
                                        row.Add("path", org.Path);
                                        row.Add("mc_influencetypeid", item.Mc_influencetypeid);
                                        List<string> idList = new List<string>();
                                        idList.Add(item.Common_id);
                                        SituationExpressAdd situationExpressAdd = new SituationExpressAdd();
                                        string situationID = situationExpressAdd.GetGroupSituationID(item.Common_id, 1, "1", idList);
                                        string ewid = situationExpressAdd.GetGroupExpressID(situationID, dataContext.DataLayerAns.CaseType);
                                        ///根据组合情节获取表述ID
                                        row.Add("ew_id", ewid);
                                        rowsdic.Add(row);
                                    }
                                }
                                s1.Stop();
                                RuleParseClass.WriteContentLog("情节结果：" + JsonConvert.SerializeObject(rowsdic) + "，耗时：" + s1.Elapsed.TotalMilliseconds.ToString("0"));

                            }
                        }
                    }
                }
                s1.Restart();
                DataSaveSituation_new(rowsdic, dataModelAsisModelList, parid);
                s1.Stop();
                RuleParseClass.WriteContentLog("执行数据保存耗时：" + s1.Elapsed.TotalMilliseconds.ToString("0"));
            }

            swtext.Stop();
            base.dataContext.InteractiveShow.LogShow(" *********************@情节提取结束耗时：" + swtext.Elapsed.TotalMilliseconds.ToString("0") + "****************************");
        }


        /// <summary>
        /// 情节表数据做补充(案由提取模块)
        /// </summary>
        public void MatchPlotSupplementCasuse(List<DataModel> dataModelAsisModelList, string parid)
        {
            if (base.dataContext.DataLayerAns.CaseCausesList == null || base.dataContext.DataLayerAns.CaseCausesList.Count() == 0)
            {
                base.dataContext.InteractiveShow.LogShow(" 当前案由未获取到，不进行情节的分析！");
                return;
            }

            base.dataContext.InteractiveShow.LogShow(" *********************@开始情节提取****************************");

            Stopwatch swtext = new Stopwatch();
            swtext.Start();

            //是否机器学习
            bool isMatchLearn = false;
            SituationPlotMLCaseType mlCaseType = null;
            if (mlConfigModel != null)
            {
                mlCaseType = mlConfigModel.CaseTypes.FirstOrDefault(x => x.Value == dataContext.DataLayerAns.CaseType);
                if (mlCaseType != null)
                    isMatchLearn = true;
            }
            foreach (var causeModel in dataContext.DataLayerAns.CaseCausesList)
            {
                List<Dictionary<string, string>> rowsdic = new List<Dictionary<string, string>>();

                Dictionary<string, List<ForeignKey>> extorgtext = ExtPlotContent(causeModel.CC_ID, "", dataModelAsisModelList, parid);
                base.dataContext.InteractiveShow.LogShow("匹配到的原文为:" + JsonConvert.SerializeObject(extorgtext));
                string cc_id = causeModel.CC_ID;
                foreach (var dicorg in extorgtext)
                {
                    foreach (ForeignKey org in dicorg.Value)
                    {
                        List<CommonPlotorSituation> models = new List<CommonPlotorSituation>();
                        //执行拆句
                        var sentences = base.SentenceSplitting(org.Oringtext, org.paragraphCode, circumsatanModel, "1", causeModel.CC_ID, false);
                        if (sentences != null && sentences.Any())
                        {
                            List<SentenceModel> regSentences = new List<SentenceModel>();

                            if (isMatchLearn == true && org.isml == "1")
                            {
                                base.dataContext.InteractiveShow.LogShow("使用机器学习开始:" + JsonConvert.SerializeObject(sentences));
                                Stopwatch swtext1 = new Stopwatch();
                                swtext1.Start();

                                regSentences.AddRange(sentences);
                                List<CommonPlotorSituation> matchLearnModels = new List<CommonPlotorSituation>();
                                foreach (var sentenceItem in sentences)
                                {
                                    if (!string.IsNullOrWhiteSpace(sentenceItem.SentenceContent))
                                    {
                                        List<SYS_CaseCause> causes = new List<SYS_CaseCause>();
                                        var recognition = mlCaseType.Recognitions.FirstOrDefault(x => x.MatchType == 2);
                                        if (recognition != null)
                                        {
                                            //机器学习编码集合
                                            List<string> machCodes = new List<string>();
                                            var commonCode = recognition.CommonCode;
                                            //获取通用情节机器学习编码
                                            if (!string.IsNullOrWhiteSpace(commonCode))
                                            {
                                                var commonMachCodes = commonCode.Split(',');
                                                foreach (var codeItem in commonMachCodes)
                                                {
                                                    if (!string.IsNullOrWhiteSpace(codeItem))
                                                        machCodes.Add(codeItem);
                                                }
                                            }
                                            //获取个罪机器学习编码
                                            var causeRecogns = recognition.Causes;
                                            if (causeRecogns != null && recognition.Causes.Any())
                                            {
                                                var causeRecogn = causeRecogns.FirstOrDefault(x => x.Value.Contains(cc_id));
                                                if (causeRecogn != null)
                                                {
                                                    var mlCode = causeRecogn.mlcode;
                                                    if (!string.IsNullOrWhiteSpace(mlCode))
                                                    {
                                                        var causeMachCodes = mlCode.Split(',');
                                                        foreach (var codeItem in causeMachCodes)
                                                        {
                                                            if (!string.IsNullOrWhiteSpace(codeItem))
                                                                machCodes.Add(codeItem);
                                                        }
                                                    }
                                                }
                                            }
                                            if (machCodes != null && machCodes.Any())
                                            {
                                                foreach (var item in machCodes)
                                                {
                                                    //调用机器学习接口获取情节数据
                                                    var machModels = GetCausesByMachineLearn(sentenceItem.SentenceContent, item, "2");
                                                    if (machModels != null && machModels.Any())
                                                        causes.AddRange(machModels);
                                                }
                                            }
                                        }
                                        if (causes.Any())
                                        {
                                            causes = causes.Distinct().ToList();
                                            var matchSuccess = base.LoopExtractMatchLearn(sentenceItem, causes, ref matchLearnModels);
                                            if (matchSuccess)
                                            {
                                                models.AddRange(matchLearnModels);
                                                regSentences.Remove(sentenceItem);
                                            }
                                        }
                                    }
                                }

                                swtext1.Stop();
                                base.dataContext.InteractiveShow.LogShow("使用机器学习调用时长:" + swtext1.Elapsed.TotalMilliseconds.ToString("0"));
                            }
                            else
                            {
                                regSentences = sentences;
                            }
                            if (regSentences != null && regSentences.Any())
                            {
                                if (org.type != "3")
                                {
                                    CommElementRegexCode commElement = new CommElementRegexCode();
                                    commElement.CaseType = base.dataContext.DataLayerAns.CaseType;
                                    commElement.SourceCode = base.dataContext.DataLayerAns.SourceCode;
                                    commElement.PargarphCode = "xs_cr_courttrialend";
                                    commElement.PargarphWhere = dicorg.Key == "convicted" ? "=" : "<>";

                                    commElement.Purpose = ExtractType.plotorsituation;
                                    bool isRuleitem = (causeModel.CC_DevelopSchedule == 1 || causeModel.CC_DevelopSchedule == 2) ? true : false;
                                    string match = isRuleitem ? "Regex" : "RuleItem";
                                    base.dataContext.InteractiveShow.LogShow("*进行情节提取：当前案由的匹配规则为：" + match);
                                    if (regSentences.Any(x => x.SentenceType == "0"))
                                    {
                                        string affirmContent = string.Join("", regSentences.Where(x => x.SentenceType == "0").Select(x => x.SentenceContent));
                                        var affirmModels = MatchValueID(cc_id, isRuleitem, affirmContent, commElement, "0", "",org.isml);
                                        if (affirmModels != null && affirmModels.Any())
                                            models.AddRange(affirmModels);
                                    }
                                    if (regSentences.Any(x => x.SentenceType == "1"))
                                    {
                                        string unAffirmContent = string.Join("", regSentences.Where(x => x.SentenceType == "1").Select(x => x.SentenceContent));
                                        var unAffirmModels = MatchValueID(cc_id, isRuleitem, unAffirmContent, commElement, "1", "",org.isml);
                                        if (unAffirmModels != null && unAffirmModels.Any())
                                            models.AddRange(unAffirmModels);
                                    }
                                }
                                else if (org.type == "3")
                                {
                                    CommElementRegexCode commElement = new CommElementRegexCode();
                                    commElement.CaseType = base.dataContext.DataLayerAns.CaseType;
                                    commElement.SourceCode = base.dataContext.DataLayerAns.SourceCode;
                                    commElement.PargarphCode = "xs_cr_courttrialend";
                                    commElement.PargarphWhere = dicorg.Key == "convicted" ? "=" : "<>";

                                    commElement.Purpose = ExtractType.plotorsituation;
                                    bool isRuleitem = (causeModel.CC_DevelopSchedule == 1 || causeModel.CC_DevelopSchedule == 2) ? true : false;
                                    string match = isRuleitem ? "Regex" : "RuleItem";
                                    base.dataContext.InteractiveShow.LogShow("*进行情节提取：当前案由的匹配规则为：" + match);
                                    if (regSentences.Any(x => x.SentenceType == "0"))
                                    {
                                        string affirmContent = string.Join("", regSentences.Where(x => x.SentenceType == "0").Select(x => x.SentenceContent));
                                        var affirmModels = CommMatchValueID(org.Oringtext, commElement, "0",org.isml);
                                        if (affirmModels != null && affirmModels.Any())
                                            models.AddRange(affirmModels);
                                    }
                                    if (regSentences.Any(x => x.SentenceType == "1"))
                                    {
                                        string unAffirmContent = string.Join("", regSentences.Where(x => x.SentenceType == "1").Select(x => x.SentenceContent));
                                        var unAffirmModels = CommMatchValueID(org.Oringtext, commElement, "1", org.isml);
                                        if (unAffirmModels != null && unAffirmModels.Any())
                                            models.AddRange(unAffirmModels);
                                    }
                                }
                            }
                            if (models != null && models.Any())
                            {
                                //----------------------------------
                                //查询到的对应情节对象列表
                                foreach (var item in models)
                                {///针对相同来源的，相同的情节进行去重处理
                                    var rowplottemp = rowsdic.FirstOrDefault(rowplot => LdFormat.GetDicValue(rowplot, "po_plotid") == item.Common_id && LdFormat.GetDicValue(rowplot, "po_plotsource") == dicorg.Key && LdFormat.GetDicValue(rowplot, "sp_id") == org.Fk);
                                    if (rowplottemp == null)
                                    {
                                        Dictionary<string, string> row = new Dictionary<string, string>();
                                        row.Add("plotid", "");
                                        row.Add("sp_id", org.Fk);
                                        row.Add("po_ismatch", "1");
                                        row.Add("po_singlecrimeid", "");
                                        row.Add("po_matchsource", base.dataContext.DataLayerAns.SourceCode);
                                        row.Add("po_affirmidearesult", item.Common_affirm);
                                        row.Add("po_plotsource", dicorg.Key);
                                        row.Add("po_typeid", item.Common_typeid);
                                        row.Add("po_plotname", item.Common_name);
                                        row.Add("po_plotid", item.Common_id);
                                        row.Add("originaltext", item.Common_originalText);
                                        row.Add("mc_influencetypeid", item.Mc_influencetypeid);
                                        row.Add("path", org.Path);

                                        List<string> idList = new List<string>();
                                        idList.Add(item.Common_id);
                                        SituationExpressAdd situationExpressAdd = new SituationExpressAdd();
                                        string situationID = situationExpressAdd.GetGroupSituationID(item.Common_id, 1, "1", idList);
                                        string ewid = situationExpressAdd.GetGroupExpressID(situationID, dataContext.DataLayerAns.CaseType);
                                        ///根据组合情节获取表述ID
                                        row.Add("ew_id", ewid);
                                        rowsdic.Add(row);
                                    }
                                }
                            }
                        }
                    }
                }
                DataSaveSituation_new(rowsdic, dataModelAsisModelList, parid);
            }
            swtext.Stop();
            base.dataContext.InteractiveShow.LogShow(" *********************@情节提取结束耗时：" + swtext.Elapsed.TotalMilliseconds.ToString("0") + "****************************");

        }
        /// <summary>
        /// 数据保存
        /// </summary>
        /// <param name="DataModelDic"></param>
        public void DataSaveSituation_new(List<Dictionary<string, string>> DataModelDic, List<DataModel> dataModelAsisModelList, string parid)
        {
            DataSoursModel dataSoursModel = new DataSoursModel();
            dataSoursModel.dataModelList = dataModelAsisModelList;
            foreach (Dictionary<string, string> dicValue in DataModelDic)
            {
                string path = dicValue["sp_id"];
                DataModel dataModelParent = dataSoursModel.dataModelList.FirstOrDefault(a => a.ID == path);
                if (dataModelParent == null)
                {
                    CaseNodeUpdate(dataSoursModel.dataModelList, path);
                    dataModelParent = dataSoursModel.dataModelList.FirstOrDefault(a => a.XmlPath == path);
                    DataSaveAtticeton(dataModelParent, dicValue);
                }
                else
                {
                    DataModel dataModel = new DataModel();
                    dataModel.XmlPath = dataModelParent.XmlPath + "/详情";
                    dataModel.ParentId = dataModelParent.ID;
                    dataModel.sourceData = new SourceData();
                    dataModel.ID = Snowflake.Instance().GetId().ToString();
                    Source source = new Source();
                    source.SourceCode = dataContext.DataLayerAns.SourceCode;
                    source.IsCheck = "1";
                    dataModel.sourceData.sourceList = new List<Source>();
                    dataModel.sourceData.sourceList.Add(source);
                    DataSaveAtticeton(dataModel, dicValue);
                    dataSoursModel.dataModelList.Add(dataModel);
                    var originaltext = dicValue["originaltext"];
                    if (!string.IsNullOrWhiteSpace(originaltext))
                    {
                        DataModel originalDataModel = new DataModel();
                        originalDataModel.XmlPath = dataModelParent.XmlPath + "/详情/原文";
                        originalDataModel.ParentId = dataModel.ID;
                        originalDataModel.sourceData = new SourceData();
                        originalDataModel.ID = Snowflake.Instance().GetId().ToString();
                        Source originalSource = new Source();
                        originalSource.SourceCode = dataContext.DataLayerAns.SourceCode;
                        originalSource.IsCheck = "1";
                        originalDataModel.sourceData.sourceList = new List<Source>();
                        originalDataModel.sourceData.sourceList.Add(originalSource);
                        originalDataModel.AttributesList = new List<AttributeInfo>();
                        SetAttion("原文", originaltext, originalDataModel);
                        dataSoursModel.dataModelList.Add(originalDataModel);
                    }
                }

            }
            XmlDocument xmlDocumentp = XmlUtility.DataModelByXml(dataSoursModel.dataModelList);
        }
        /// <summary>
        /// 数据保存
        /// </summary>
        /// <param name="DataModelDic"></param>
        public void DataSaveSituation(List<Dictionary<string, string>> DataModelDic)
        {
            DataSoursModel dataSoursModel = dataContext.DataLayerAns.AnalysisResultsDataModel;
            foreach (Dictionary<string, string> dicValue in DataModelDic)
            {
                string path = dicValue["path"];
                DataModel dataModelParent = dataSoursModel.dataModelList.FirstOrDefault(a => a.XmlPath == path);
                if (dataModelParent == null)
                {
                    CaseNodeUpdate(dataSoursModel.dataModelList, path);
                    dataModelParent = dataSoursModel.dataModelList.FirstOrDefault(a => a.XmlPath == path);
                    DataSaveAtticeton(dataModelParent, dicValue);
                }
                else
                {
                    DataModel dataModel = new DataModel();
                    dataModel.XmlPath = dataModelParent.XmlPath;
                    dataModel.ParentId = dataModelParent.ParentId;
                    dataModel.sourceData = new SourceData();
                    dataModel.ID = Snowflake.Instance().GetId().ToString();
                    Source source = new Source();
                    source.SourceCode = dataContext.DataLayerAns.SourceCode;
                    source.IsCheck = "1";
                    dataModel.sourceData.sourceList = new List<Source>();
                    dataModel.sourceData.sourceList.Add(source);
                    DataSaveAtticeton(dataModel, dicValue);
                    dataSoursModel.dataModelList.Add(dataModel);
                    var originaltext = dicValue["originaltext"];
                    if (!string.IsNullOrWhiteSpace(originaltext))
                    {
                        DataModel originalDataModel = new DataModel();
                        originalDataModel.XmlPath = dataModelParent.XmlPath + "/原文";
                        originalDataModel.ParentId = dataModel.ID;
                        originalDataModel.sourceData = new SourceData();
                        originalDataModel.ID = Snowflake.Instance().GetId().ToString();
                        Source originalSource = new Source();
                        originalSource.SourceCode = dataContext.DataLayerAns.SourceCode;
                        originalSource.IsCheck = "1";
                        originalDataModel.sourceData.sourceList = new List<Source>();
                        originalDataModel.sourceData.sourceList.Add(originalSource);
                        originalDataModel.AttributesList = new List<AttributeInfo>();
                        SetAttion("原文", originaltext, originalDataModel);
                        dataSoursModel.dataModelList.Add(originalDataModel);
                    }

                }
            }
            dataContext.DataLayerAns.AnalysisResultsDataModel = dataSoursModel;
            XmlDocument xmlDocumentp = XmlUtility.DataModelByXml(dataSoursModel.dataModelList);
            dataContext.DataLayerAns.AnalysisResultsXml = xmlDocumentp;
        }

        /// <summary>
        /// 保存数据
        /// </summary>
        /// <param name="dataModel"></param>
        public void DataSaveAtticeton(DataModel dataModel, Dictionary<string, string> DicValue)
        {
            dataModel.AttributesList = new List<AttributeInfo>();
            AttributeInfo attribute = new AttributeInfo();
            SetAttion("情节ID", DicValue["po_plotid"], dataModel);
            SetAttion("情节名称", DicValue["po_plotname"], dataModel);
            SetAttion("情节来源", DicValue["po_plotsource"], dataModel);
            SetAttion("情节认定意见结果", DicValue["po_affirmidearesult"], dataModel);
            SetAttion("表述ID", DicValue["ew_id"], dataModel);
            if (DicValue.ContainsKey("po_typeid"))
            {
                SetAttion("量刑因素种类", DicValue["po_typeid"], dataModel);
            }
            if (DicValue.ContainsKey("mc_influencetypeid"))
            {
                SetAttion("量刑情节种类", DicValue["mc_influencetypeid"], dataModel);
            }

        }

        public void SetAttion(string attributeName, string attributeValue, DataModel dataModel)
        {
            AttributeInfo attribute = new AttributeInfo();
            attribute.Name = attributeName;
            attribute.sourceList = new List<Source>();
            Source source = new Source();
            source.SaveValue = attributeValue;
            source.SourceCode = dataContext.DataLayerAns.SourceCode;
            source.IsCheck = "1";
            attribute.sourceList.Add(source);
            dataModel.AttributesList.Add(attribute);

        }
        /// <summary>
        /// 获取情节配置
        /// </summary>
        /// <param name="tbl_id"></param>
        /// <param name="xmldoc"></param>
        /// <param name="dataModelAnalysisList"></param>
        /// <param name="parid"></param>
        /// <returns></returns>
        private Dictionary<string, List<ForeignKey>> ExtPlotContent(string tbl_id, string xmldoc, List<DataModel> dataModelAnalysisList, string parid)
        {
            XmlUtilCommon xmlUtilCommon = new XmlUtilCommon() { dataContext = dataContext };
            Dictionary<string, List<ForeignKey>> orgtext = new Dictionary<string, List<ForeignKey>>();
            List<ParagraphModel> paragraphlList = new List<ParagraphModel>();
            if (paragraphModelList.Count == 0 && circumsatanModel != null && circumsatanModel.casetypeModelList.Count > 0)
            {
                CasetypeModel casetypeModel = circumsatanModel.casetypeModelList.FirstOrDefault(a => a.Code.ToLower() == dataContext.DataLayerAns.CaseType.ToLower());
                if (casetypeModel != null)
                {
                    List<ParagraphModel> modelList = new List<ParagraphModel>();
                    paragraphlList = casetypeModel.docTypeList.FirstOrDefault(a => a.Code.ToLower() == dataContext.DataLayerAns.SourceCode.ToLower()).paragraphModelList;
                    try
                    {
                       
                        List<ParagraphModel> paragraphCauseList = paragraphlList.Where(a => a.causecode == tbl_id).ToList();
                        List<ParagraphModel> paragraphCauseNotList = paragraphlList.Where(a => a.causecode == null || a.causecode == "").ToList();
                        if (paragraphCauseList == null || paragraphCauseList.Count == 0)
                        {
                            modelList = paragraphCauseNotList;
                        }
                        else if (paragraphCauseList.Count > 0)
                        {
                            if (modelList.Count == 0)
                            {
                                modelList = paragraphCauseList;
                            }
                            else
                            {
                                foreach (var model in paragraphCauseNotList)
                                {
                                    if (modelList.FirstOrDefault(a => a.Code == model.Code) == null)
                                    {
                                        modelList.Add(model);
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {

                        modelList = paragraphlList;
                    }
                   
                    foreach (var casevalue in modelList)
                    {
                        foreach (var pathvlaue in casevalue.pathModelList)
                        {

                            if (pathvlaue.Type == "2" || pathvlaue.Type == "3")
                            {
                                string xpath = pathvlaue.value.Replace("{causecode}", tbl_id);
                                foreach (DataModel dataModel in XmlUtility.ConditionDataModelList(dataContext.DataLayerAns.AnalysisResultsDataModel.dataModelList, "", xpath))
                                {
                                    ForeignKey key = new ForeignKey();
                                    key.Oringtext = HttpHelp.DeCodeBase64new(65001, dataModel.sourceData.sourceList.FirstOrDefault(a => a.IsCheck == "1").SaveValue);
                                    key.Fk = dataModel.ID;
                                    key.Path = casevalue.pathModelList.FirstOrDefault(a => a.Type == "2").value;
                                    key.paragraphCode = casevalue.Code;
                                    key.type = pathvlaue.Type;
                                    key.isml = casevalue.isml;
                                    if (orgtext.ContainsKey(casevalue.Type))
                                    {
                                        orgtext[casevalue.Type].Add(key);
                                    }
                                    else
                                    {
                                        List<ForeignKey> Keylist = new List<ForeignKey>();
                                        Keylist.Add(key);
                                        orgtext.Add(casevalue.Type, Keylist);
                                    }
                                }
                            }
                        }

                    }
                }
            }
            else if (paragraphModelList != null)
            {

                List<ParagraphModel> modelList = new List<ParagraphModel>();
                paragraphlList = paragraphModelList;
                try
                {
                    List<ParagraphModel> paragraphCauseList = paragraphlList.Where(a => a.causecode == tbl_id).ToList();
                    List<ParagraphModel> paragraphCauseNotList = paragraphlList.Where(a => a.causecode == null || a.causecode == "").ToList();
                    if (paragraphCauseList == null || paragraphCauseList.Count == 0)
                    {
                        modelList = paragraphCauseNotList;
                    }
                    else if (paragraphCauseList.Count > 0)
                    {
                        if (modelList.Count == 0)
                        {
                            modelList = paragraphCauseList;
                        }
                        else
                        {
                            foreach (var model in paragraphCauseNotList)
                            {
                                if (modelList.FirstOrDefault(a => a.Code == model.Code) == null)
                                {
                                    modelList.Add(model);
                                }
                            }
                        }
                    }
                }
                catch (Exception)
                {

                    modelList= paragraphlList;
                }
               

                foreach (var casevalue in modelList)
                {
                    foreach (var pathvlaue in casevalue.pathModelList)
                    {
                        if (pathvlaue.Type == "2" || pathvlaue.Type == "3")
                        {
                            List<string> valueList = pathvlaue.value.Split(new string[] { "事实要素" }, System.StringSplitOptions.None).ToList();

                            string pathvalue = "";
                            if (valueList.Count > 0)
                            {
                                pathvalue = valueList[0] + "事实要素";

                            }
                            string xpath = pathvlaue.value.Replace("{causecode}", tbl_id);
                            foreach (DataModel dataModel in XmlUtility.ConditionDataModelList(dataModelAnalysisList, parid, xpath))
                            {
                                string suitid = "";
                                List<DataModel> dataModeElmentlList = xmlUtilCommon.SubParentDateModel(dataModelAnalysisList, dataModel);
                                DataModel dataModelRoot = dataModeElmentlList.FirstOrDefault(a => a.XmlPath == pathvalue);
                                if (dataModelRoot != null)
                                {
                                    if (dataModelAnalysisList.FirstOrDefault(a => a.ParentId == dataModelRoot.ID) != null)
                                    {
                                        DataModel dataModelRootzfg = dataModelAnalysisList.FirstOrDefault(a => a.ParentId == dataModelRoot.ID && a.XmlPath.IndexOf("主张方") > -1);
                                        if (dataModelRootzfg != null)
                                        {
                                            string id = dataModelRootzfg.AttributesList.FirstOrDefault(a => a.Name == "主张方诉讼地位").sourceList.FirstOrDefault(a => a.IsCheck == "1").SaveValue;
                                            if (id == "306")
                                            {
                                                suitid = "investigate";
                                            }
                                            else if (id == "164")
                                            {
                                                suitid = "legation";
                                            }
                                            else if (id == "1")
                                            {
                                                suitid = "defense";
                                            }
                                        }
                                    }
                                }
                                ForeignKey key = new ForeignKey();
                                key.Oringtext = HttpHelp.DeCodeBase64new(65001, dataModel.sourceData.sourceList.FirstOrDefault(a => a.IsCheck == "1").OriginalText);
                                key.Fk = dataModel.ID;
                                key.Path = casevalue.pathModelList.FirstOrDefault(a => a.Type == "2").value;
                                key.type = pathvlaue.Type;
                                key.paragraphCode = casevalue.Code;
                                key.isml = casevalue.isml;
                                if (orgtext.ContainsKey(suitid))
                                {
                                    orgtext[suitid].Add(key);
                                }
                                else
                                {
                                    List<ForeignKey> Keylist = new List<ForeignKey>();
                                    Keylist.Add(key);
                                    orgtext.Add(suitid, Keylist);
                                }
                            }
                        }
                    }
                }
            }
            return orgtext;
        }

        #endregion
    }
}
